/**
 * Dialog 提示框
 */
import dayjs from 'dayjs';
import { ref } from 'vue';
import { useModalStore } from '@/store';
import test from '@/utils/test';
import { sendCode } from '@/api/user';

export default function useModal() {
  const showModal = (content: string, options: UniApp.ShowModalOptions) => {
    return new Promise((resolve, reject) => {
      uni.showModal({
        title: '温馨提示',
        content,
        showCancel: false,
        confirmColor: '#1677FF',
        success: res => resolve(res),
        fail: () => reject(new Error('Alert 调用失败 !')),
        ...options,
      });
    });
  };

  // 打开授权弹框
  function showAuthModal(type = 'smsLogin') {
    const modal = useModalStore();
    console.log('modal=====', modal);
    // #ifdef H5
    closeAuthModal();
    setTimeout(() => {
      modal.$patch((state: any) => {
        state.auth = type;
      });
    }, 200);
    // #endif

    // #ifndef H5
    modal.$patch((state: any) => {
      state.auth = type;
    });
  // #endif
  }

  // 关闭授权弹框
  function closeAuthModal() {
    useModalStore().$patch((state: any) => {
      state.auth = '';
    });
  }

  // 打开分享弹框
  function showShareModal() {
    useModalStore().$patch((state: any) => {
      state.share = true;
    });
  }

  // 关闭分享弹框
  function closeShareModal() {
    useModalStore().$patch((state: any) => {
      state.share = false;
    });
  }

  // 打开快捷菜单
  function showMenuTools() {
    useModalStore().$patch((state: any) => {
      state.menu = true;
    });
  }

  // 关闭快捷菜单
  function closeMenuTools() {
    useModalStore().$patch((state: any) => {
      state.menu = false;
    });
  }

  // 发送短信验证码  60秒
  function getSmsCode(event: 'smsLogin' | 'changeMobile' | 'resetPassword' | 'changePassword', mobile: any) {
    const modalStore = useModalStore();
    console.log('getSmsCode', modalStore);
    const lastSendTimer = modalStore.lastTimer[event];
    if (typeof lastSendTimer === 'undefined') {
      uni.$u.toast('短信发送事件错误');
      return;
    }

    const duration = dayjs().unix() - lastSendTimer;
    const canSend = duration >= 60;
    if (!canSend) {
      uni.$u.toast('请稍后再试');
      return;
    }
    // 只有 mobile 非空时才校验。因为部分场景（修改密码），不需要输入手机
    if (mobile && !test.mobile(mobile)) {
      uni.$u.toast('手机号码格式不正确');
      return;
    }

    // 发送验证码 + 更新上次发送验证码时间
    let scene = -1;
    switch (event) {
      case 'resetPassword':
        scene = 4;
        break;
      case 'changePassword':
        scene = 3;
        break;
      case 'changeMobile':
        scene = 2;
        break;
      case 'smsLogin':
        scene = 1;
        break;
    }
    sendCode({ mobile, scene }).then((res: any) => {
      if (res.code === 0) {
        modalStore.$patch((state: any) => {
          state.lastTimer[event] = dayjs().unix();
        });
      }
    });
  }

  // 获取短信验证码倒计时 -- 60秒
  function getSmsTimer(event: 'smsLogin' | 'changeMobile' | 'resetPassword' | 'changePassword') {
    const modalStore = useModalStore();
    const lastSendTimer = modalStore.lastTimer[event];

    if (typeof lastSendTimer === 'undefined') {
      uni.$u.toast('短信发送事件错误');
      return;
    }

    const duration = ref(dayjs().unix() - lastSendTimer - 60);
    const canSend = duration.value >= 0;

    if (canSend) {
      return '获取验证码';
    }

    if (!canSend) {
      setTimeout(() => {
        duration.value++;
      }, 1000);
      return `${-duration.value.toString()} 秒`;
    }
  }

  // 记录广告弹框历史
  function saveAdvHistory(adv: any) {
    const modal = useModalStore();

    modal.$patch((state: any) => {
      if (!state.advHistory.includes(adv.imgUrl)) {
        state.advHistory.push(adv.imgUrl);
      }
    });
  }
  return {
    showModal,
    showAuthModal,
    closeAuthModal,
    showShareModal,
    closeShareModal,
    showMenuTools,
    closeMenuTools,
    getSmsCode,
    getSmsTimer,
    saveAdvHistory,
  };
}
